package com.lianqi.emcpframework.ddd.gencode.creator;

import java.lang.annotation.Annotation;

import javax.lang.model.element.TypeElement;

import org.apache.commons.lang3.StringUtils;

import com.lianqi.emcpframework.ddd.gencode.EnableGenForAggregate;
import com.lianqi.emcpframework.ddd.gencode.EnableGenForEntity;

import lombok.AccessLevel;
import lombok.Getter;

@Getter(AccessLevel.PUBLIC)
public class GenCreatorParser {
    private final TypeElement typeElement;

    private GenCreatorType type;
    private String packageName;
    private String className;
    private String parentClassName;

    public GenCreatorParser(TypeElement typeElement) {
        this.typeElement = typeElement;
    }

    public void read(Annotation annotation) {
        if (annotation instanceof GenCreator) {
            readFromGenCreator((GenCreator)annotation);
        }
        if (annotation instanceof EnableGenForAggregate) {
            readFromEnableGenForAggregate((EnableGenForAggregate)annotation);
        }
        if (annotation instanceof EnableGenForEntity) {
            readFromEnableGenForEntity((EnableGenForEntity)annotation);
        }
    }

    /**
     * 生成updater name
     *
     * @param userDriect
     * @return
     */
    String buildClassName(boolean userDriect) {

        if (userDriect) {
            return typeElement.getSimpleName().toString() + "Creator";
        } else {
            return "Base" + typeElement.getSimpleName().toString() + "Creator";
        }
    }

    private String defaultPackageName() {
        return typeElement.getEnclosingElement().toString().replace(".domain.", ".base.domain.");
    }

    private void readFromEnableGenForEntity(EnableGenForEntity annotation) {
        this.type = GenCreatorType.JAVA_BEAN;
        this.packageName = defaultPackageName();
        this.className = buildClassName(annotation.useCreatorDirect());
        this.parentClassName = "";
    }

    private void readFromEnableGenForAggregate(EnableGenForAggregate annotation) {
        this.type = GenCreatorType.JAVA_BEAN;
        this.packageName = defaultPackageName();
        this.className = buildClassName(annotation.useCreatorDirect());
        this.parentClassName = "";
    }

    private void readFromGenCreator(GenCreator genCreator) {
        this.type = genCreator.type();
        this.packageName = defaultPackageName();
        this.className = buildClassName(genCreator.useDirect());
        if (StringUtils.isNotEmpty(genCreator.parent())) {
            this.parentClassName = genCreator.parent();
        }
    }
}
